import type { VNode, RenderType, RenderDataType, SSMLRenderNode, RenderNodeId } from './type'
import { SSMLTagEnum } from './type'
import { engReg, numReg, hanReg, conjReg } from '../regexp'

export const getType = (data: string) => {
  let type: RenderType = 'text'
  if (engReg.test(data) || numReg.test(data)) {
    type = SSMLTagEnum.SAY_AS
  }
  if (hanReg.test(data)) {
    type = SSMLTagEnum.PHONEME
  }
  return type
}

export const getDataType = (data: string, tag: RenderType) => {
  let dataType: RenderDataType = 'text'
  switch (tag) {
    case SSMLTagEnum.BREAK: {
      dataType = 'break'
      break
    }
    case SSMLTagEnum.SAY_AS: {
      if (engReg.test(data)) {
        dataType = 'word'
      } else if (numReg.test(data)) {
        dataType = 'number'
      } else {
        dataType = 'text'
      }
      break
    }
    case SSMLTagEnum.PHONEME: {
      if (/^[\u4e00-\u9fa5]+$/.test(data)) {
        dataType = 'chinese'
      } else {
        dataType = 'text'
      }
      break
    }
    default: {
      dataType = 'text'
    }
  }
  return dataType
}

export const getMarkByAttrib = (type: string) => {
  return {
    currency: '数值',
    number: '数值',
    telephone: '电话',
    digits: '数字',
    id: '字母',
    letter: '字母',
  }[type]
}

export const getMarkByTime = (time: string) => {
  if (!time || time === '1000ms' || time === '1s') {
    return '中'
  }
  if (time === '500ms') {
    return '短'
  }
  if (time === '2000ms' || time === '2s') {
    return '长'
  }
  return time
}

export const getMarked = (node: VNode) => {
  const { name, attribs = {} } = node
  switch (name) {
    case SSMLTagEnum.PHONEME: return !!attribs['ph']
    case SSMLTagEnum.SAY_AS: return !!attribs['interpret-as']
    case SSMLTagEnum.BREAK: return true
  }
}

export const checkConjunction = (sentence: string) => {
  const words: Array<RegExpExecArray> = []
  let current: RegExpExecArray | null = null
  conjReg.lastIndex = 0

  do {
    current = conjReg.exec(sentence)
    current && words.push(current)
  } while (current)

  return words
}

export const genTextNode = (data: string, id: RenderNodeId): SSMLRenderNode => {
  return {
    id,
    type: 'text',
    data,
    attribs: {},
  }
}

export const genRenderNode = (type: RenderType, dataType: RenderDataType, data: string, id: RenderNodeId): SSMLRenderNode => {
  return {
    attribs: {},
    data,
    id,
    type,
    dataType,
  }
}

export const genBreakNode = (duration = '1s', id: RenderNodeId): SSMLRenderNode => {
  return {
    id,
    type: SSMLTagEnum.BREAK,
    data: ' ',
    mark: '中',
    label: '中',
    dataType: 'break',
    attribs: {
      time: duration,
    },
  }
}

export const genLineBreakNode = (id: RenderNodeId): SSMLRenderNode => {
  return {
    id,
    type: 'text',
    data: '\n',
    dataType: 'lineBreak',
    attribs: {},
    checked: true,
  }
}
